<?php

namespace App\Console\Commands;
use Illuminate\Support\Facades\Storage;

use Illuminate\Console\Command;
use App\Models\News\NewsClass;
use App\Models\News\News;
use App\Helper\Build\Build;
class BuildColumn extends Command
{
    use SetUserAndGroup;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'build:column';
    protected $play_class_build_key = 'play_class_build';

    protected $limit = 20;
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成栏目列表页';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->setUserAndGroup();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $data = cache($this->play_class_build_key);
        if(!$data)return '不存在任务';
        if($data['status'] == 2)return '已执行完成';
        $model = new NewsClass();
        $data['status'] = 1;
        cache([$this->play_class_build_key=>$data], 30000);
        if(!empty($data['class_id']) && is_array($data['class_id']))
        {
            $ids = [];
            foreach ($data['class_id'] as $key => $value) {
                # code...
                if(!is_null($value) && $value>0)
                {
                    $ids[] = $value;
                }
            }
            if(!empty($ids))$model = $model->whereIn('id', $data['class_id']);
            
        }
        $variable = $model->where('is_page', 0)->get();
        foreach ($variable as $key => $value) {
            # code...
            echo '============='.$value->id.'==============='.chr(10);
            $this->classList($value);
        }
        
        $data['status'] = 2;
        cache([$this->play_class_build_key=>$data], 30000);
    }

    protected function classList($info)
    {
        $Build = new Build();
        $num = News::where('status', 2)->where('class_id', $info->id)->count();
        if($info->limit_num > 0)
        {
            $this->limit = $info->limit_num;
        }
        $total =  ceil($num/$this->limit)-1;//减去1，默认首页
        $this->delete_files($info);
        for ($i=$total; $i >=0 ; $i--) { 
            # code...
            $Build->news_class($info, $i);
            echo $i.chr(10);
        }
    }
    //删除原来的文件
    protected function delete_files($info)
    {
        $files = Storage::disk('build')->files($info->alias);
        // dd($files);
        foreach ($files as $key => $value) {
            # code...
            Storage::disk('build')->delete($value);
        }
    }


    
}
